package cn.hit.tianqiao.dao.impl;

import cn.hit.tianqiao.dao.ReservationRepositoryDao;
import cn.hit.tianqiao.domain.Order;
import cn.hit.tianqiao.domain.Reservation;
import cn.hit.tianqiao.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class ReservationRepositoryDaoImpl implements ReservationRepositoryDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public Reservation save(Reservation reservation) {
        String sql = "INSERT INTO reservations (userName, userPhone, userNote, eventId, createTime, reservationNumber) VALUES (?, ?, ?, ?, ?, ?)";
        template.update(sql, reservation.getUserName(), reservation.getUserPhone(), reservation.getUserNote(), reservation.getEventId(), reservation.getCreateTime(), reservation.getReservationNumber());
        return reservation;
    }

    @Override
    public List<Reservation> findAll() {
        String sql = "SELECT * FROM reservations";
        return template.query(sql, new BeanPropertyRowMapper<>(Reservation.class));
    }

    @Override
    public List<Order> findByUserPhone(String userPhone) {
        String sql = "SELECT r.*, e.* " +
                "FROM reservations r " +
                "JOIN events e ON r.eventId = e.id " +
                "WHERE r.userPhone = ?";
        return template.query(sql, new BeanPropertyRowMapper<>(Order.class), userPhone);
    }
}
